//
//  HYYNewFeatureViewController.swift
//  Hyy9Weibo
//
//  Created by Air on 16/3/29.
//  Copyright © 2016年 hyy. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"

class HYYNewFeatureViewController: UICollectionViewController {

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //流水布局
    let layout = UICollectionViewFlowLayout()
    //父类没有init（）这个构造函数，之类不需要overridr
    init(){
        super.init(collectionViewLayout: layout)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectView()
        
    }
    // MARK: - collectionView的设置
    private func prepareCollectView(){
        
        //设置layout参数
        layout.itemSize = UIScreen.mainScreen().bounds.size
        //间距
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        //滑动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        //分页
        collectionView?.pagingEnabled = true
        //弹簧效果
        collectionView?.bounces = false
        //注册cell
        //UICollectionViewCell.self == oc  中的UICollectionViewCell class
        collectionView?.registerClass(HYYNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        
    }

}

//MARK: - UICollectionView的代理源和数据方法
extension HYYNewFeatureViewController {
  
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HYYNewFeatuerPageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //从缓存池里获得cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! HYYNewFeatureCell
        cell.backgroundColor = UIColor.random()
        
        //设置cell要显示的页码
        cell.index = indexPath.item
        
        //不能在这里调用动画
//        cell.startButtonAnimation()
        
        return cell
        
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        //计算当前页
        let page = Int (scrollView.contentOffset.x / UIScreen.mainScreen().bounds.width)
        //判断当前是否是最后一页
        if page == HYYNewFeatuerPageCount - 1 {
            //让开始按钮动画
            
            //由于在这里不能调用cel，所以创建indexpath取得对应cell
            let indexPath = NSIndexPath(forItem: page, inSection: 0)
            let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! HYYNewFeatureCell
            
            //开始动画
            cell.startButtonAnimation()
        }
    }
}

//自定义的cell
class HYYNewFeatureCell: UICollectionViewCell {
    
    //MARK: - 属性
    /// 当前显示页数
    var index: Int = 0 {
        didSet{
            //在控制器设置了页码之后，我们根据页面来显示对应的图片
            bkgImageView.image = UIImage(named: "new_feature_\(index+1)")
            //只要cell要设置图片，就隐藏按钮
            startButton.hidden = true
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    func startButtonAnimation(){
        
        startButton.hidden = false
        
        //在开始动画之前，将transform设置为0
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: UIViewAnimationOptions(rawValue:0), animations: {
            //清空transform变成原来一样
            self.startButton.transform = CGAffineTransformIdentity
            }, completion: nil  )
        

    }
    //MARK: - 按钮点击事件
    func didClickStartButton(){
        //切换到mainviewcontroller
//        let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//        appDelegate?.window?.rootViewController = HYYMainViewController()
//        appDelegate?.swithRootViewController(HYYMainViewController())
        AppDelegate.outSwitchRootViewController(HYYMainViewController())
    }
    
    private func prepareUI(){
        //1.添加子控件,注意往contentView添加
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        //2.添加约束
        //背景,填充父控件
        bkgImageView.translatesAutoresizingMaskIntoConstraints = false
        
        //bkgImageView要添加约束view
        //snp_makeConstraints添加约束
        //make要添加约束view
        bkgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)//.offset(UIEdgeInsetsMake(10, 10, -10, -10))
        }
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        //开始按钮
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
//        startButton.snp_makeConstraints { (make) in
//            make.centerX.equalTo(contentView.snp_centerX)
//            make.bottom.equalTo(contentView.snp_bottom).offset(-160)
//        }
//
        startButton.snp_makeConstraints { (make) in
            //当约束view属性和参照物view的属性一样可以省略参照view的.snp_属性
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
        
        
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        
    }
    
    //MARK: - 懒加载
     /// 背景
    private lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    private lazy var startButton:UIButton = {
        let button = UIButton()
        //设置按钮
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named:"new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named:"new_feature_finish_button"), forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(HYYNewFeatureCell.didClickStartButton), forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    
}